<template>
  <div class="search-results">
    <NavBar />
    <main class="container">
      <h1>搜索结果</h1>
      <p class="search-info" v-if="searchQuery">
        关键词: <span class="search-keyword">{{ searchQuery }}</span>
        <span v-if="allBooks.length > 0">(找到 {{ allBooks.length }} 条结果)</span>
        <span v-else>(未找到相关结果)</span>
      </p>
      
      <LoadingSpinner v-if="isLoading" message="正在搜索书籍..." />
      
      <div v-else-if="allBooks.length > 0">
        <div class="filters">
          <div class="filter-group">
            <label>价格区间:</label>
            <select v-model="priceFilter">
              <option value="all">全部价格</option>
              <option value="0-20">20元以下</option>
              <option value="20-50">20-50元</option>
              <option value="50-100">50-100元</option>
              <option value="100+">100元以上</option>
            </select>
          </div>
          
          <div class="filter-group">
            <label>品相:</label>
            <select v-model="conditionFilter">
              <option value="all">全部品相</option>
              <option value="new">几乎全新</option>
              <option value="good">品相良好</option>
              <option value="used">有使用痕迹</option>
            </select>
          </div>
          
          <div class="filter-group">
            <label>排序方式:</label>
            <select v-model="sortBy">
              <option value="default">默认排序</option>
              <option value="price-asc">价格从低到高</option>
              <option value="price-desc">价格从高到低</option>
              <option value="condition">品相优先</option>
            </select>
          </div>
        </div>
        
        <div class="book-list" v-if="filteredBooks.length > 0">
          <div class="books-grid">
            <div class="book-card" v-for="book in filteredBooks" :key="book.id" @click="viewBookDetails(book.id)">
              <div class="book-cover">
                <img :src="getCoverUrl(book)" :alt="book.title">
              </div>
              <div class="book-info">
                <h4>{{ book.title }}</h4>
                <p class="book-author">{{ book.author }}</p>
                <p class="book-price">¥{{ book.price }}</p>
                <p class="book-seller">卖家: {{ book.seller_name }}</p>
                <div class="book-tags">
                  <span v-if="book.book_condition === 'new'" class="tag tag-new">几乎全新</span>
                  <span v-else-if="book.book_condition === 'good'" class="tag tag-good">品相良好</span>
                  <span v-else-if="book.book_condition === 'used'" class="tag tag-used">有使用痕迹</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-results">
          <p>使用当前筛选条件未找到相关书籍</p>
        </div>
      </div>
      
      <div class="no-results" v-else-if="searchQuery">
        <p>未找到与 "{{ searchQuery }}" 相关的书籍</p>
        <div class="suggestions">
          <h3>建议尝试：</h3>
          <ul>
            <li>检查搜索关键词是否有拼写错误</li>
            <li>尝试使用更简短或一般的关键词</li>
            <li>尝试使用同义词</li>
          </ul>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import defaultCover from '@/assets/OIP.jpg'

const route = useRoute()
const router = useRouter()
const searchQuery = computed(() => route.query.q || '')
const allBooks = ref([]) // 存储所有书籍数据
const priceFilter = ref('all')
const conditionFilter = ref('all')
const sortBy = ref('default')
const isLoading = ref(false)

onMounted(() => {
  if (searchQuery.value) {
    fetchSearchResults()
  }
})

// 监听搜索关键字变化
watch(() => route.query.q, (newValue) => {
  if (newValue) {
    fetchSearchResults()
  }
})

const fetchSearchResults = async () => {
  if (!searchQuery.value) return
  
  isLoading.value = true
  try {
    // 获取所有书籍
    const response = await api.book.getList({})
    
    // 输出响应进行调试
    console.log('搜索响应:', response)
    
    // 检查响应格式并提取数据
    let data = []
    if (Array.isArray(response)) {
      // 如果是数组，直接使用
      data = response
      console.log('获取搜索结果成功 (数组格式):', data)
    } else if (response && response.code == 200 && response.data) {
      // 如果是包含code和data的对象，则使用response.data
      data = response.data
      console.log('获取搜索结果成功 (对象格式):', data)
    } else {
      console.error('获取搜索结果失败: 返回格式不正确', response)
      data = [] // 失败时设置为空数组
    }
    
    // 进行前端关键字搜索
    allBooks.value = data.filter(book => {
      const keyword = searchQuery.value.toLowerCase()
      return (
        (book.title && book.title.toLowerCase().includes(keyword)) || 
        (book.author && book.author.toLowerCase().includes(keyword)) ||
        (book.seller_name && book.seller_name.toLowerCase().includes(keyword))
      )
    })
    
    console.log('关键字筛选后结果数量:', allBooks.value.length)
  } catch (error) {
    console.error('获取搜索结果失败:', error)
    allBooks.value = [] // 出错时设置为空数组
  } finally {
    isLoading.value = false
  }
}

// 价格区间过滤
const getPriceRange = (book, range) => {
  const price = parseFloat(book.price);
  switch(range) {
    case '0-20': return price <= 20;
    case '20-50': return price > 20 && price <= 50;
    case '50-100': return price > 50 && price <= 100;
    case '100+': return price > 100;
    default: return true; // 全部价格
  }
}

// 品相过滤
const getCondition = (book, condition) => {
  switch(condition) {
    case 'new': return book.book_condition === 'new';
    case 'good': return book.book_condition === 'good';
    case 'used': return book.book_condition === 'used';
    default: return true; // 全部品相
  }
}

// 监听筛选和排序条件变化
watch([priceFilter, conditionFilter, sortBy], () => {
  console.log('搜索页筛选条件变化:', {
    价格: priceFilter.value,
    品相: conditionFilter.value,
    排序: sortBy.value
  });
})

// 前端筛选和排序
const filteredBooks = computed(() => {
  if (allBooks.value.length === 0) return [];
  
  console.log('执行搜索页筛选，原始数据数量:', allBooks.value.length);
  
  // 先筛选
  let result = allBooks.value.filter(book => {
    const priceMatches = getPriceRange(book, priceFilter.value);
    const conditionMatches = getCondition(book, conditionFilter.value);
    return priceMatches && conditionMatches;
  });
  
  // 再排序
  if (sortBy.value === 'price-asc') {
    result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
  } else if (sortBy.value === 'price-desc') {
    result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
  } else if (sortBy.value === 'condition') {
    // 品相优先级：new > good > used
    const conditionValue = (condition) => {
      switch(condition) {
        case 'new': return 3;
        case 'good': return 2;
        case 'used': return 1;
        default: return 0;
      }
    };
    
    result.sort((a, b) => conditionValue(b.book_condition) - conditionValue(a.book_condition));
  }
  
  console.log('搜索页筛选后数据数量:', result.length);
  return result;
})

const viewBookDetails = (bookId) => {
  router.push(`/book/${bookId}`)
}

// 获取封面URL
const getCoverUrl = (book) => {
  if (book.cover) {
    // 如果是相对路径，添加基础URL
    if (typeof book.cover === 'string' && !book.cover.startsWith('http')) {
      return `http://localhost:8080/${book.cover}`
    }
    // 如果已经是完整URL，直接返回
    return book.cover
  }
  
  // 没有封面，使用默认图片
  return defaultCover
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 1rem;
}

.search-info {
  margin-bottom: 2rem;
  color: #4b5563;
}

.search-keyword {
  font-weight: bold;
  color: #1f2937;
}

.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f3f4f6;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-group label {
  color: #4b5563;
  font-weight: 500;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: white;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 2rem;
}

.book-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-5px);
}

.book-cover {
  height: 250px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-info {
  padding: 1rem;
}

.book-info h4 {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
  color: #1f2937;
}

.book-author {
  color: #6b7280;
  margin: 0.25rem 0;
  font-size: 0.9rem;
}

.book-price {
  font-weight: bold;
  color: #ef4444;
  margin: 0.5rem 0;
}

.book-seller {
  color: #6b7280;
  font-size: 0.9rem;
  margin: 0.25rem 0;
}

.book-tags {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.tag-new {
  background-color: #dcfce7;
  color: #166534;
}

.tag-good {
  background-color: #fef3c7;
  color: #92400e;
}

.tag-used {
  background-color: #fee2e2;
  color: #991b1b;
}

.no-results {
  text-align: center;
  padding: 3rem 0;
}

.no-results p {
  font-size: 1.2rem;
  color: #4b5563;
  margin-bottom: 2rem;
}

.suggestions {
  display: inline-block;
  text-align: left;
  background-color: #f3f4f6;
  padding: 1.5rem 2rem;
  border-radius: 8px;
}

.suggestions h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #1f2937;
}

.suggestions ul {
  margin: 0;
  padding-left: 1.5rem;
}

.suggestions li {
  margin-bottom: 0.5rem;
  color: #4b5563;
}
</style> 